<script setup lang="ts">
import {
  roleDelRoleApi,
  roleGetPermissionTreeApi,
  roleGetRoleDetailApi,
  roleGetRoleListApi,
  roleGetRoleUserDataApi,
} from '@/apis/role'
import type {
  RoleDetailI,
  RoleI,
  RolePermissionTreeI,
  RoleUserListI,
  RoleUserListItemI,
  RoleUserListParamsI,
} from '@/types/system.d.ts'
import { ref } from 'vue'
import user from '@/assets/user.svg'
import activeUser from '@/assets/user-active.svg'
import { addKey } from '@/utils/format'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
// 角色列表
const roleList = ref<RoleI[]>([])
// 权限树
const permissionTree = ref<RolePermissionTreeI[]>([])
// 记录当前点击的角色roleId
const currentRoleId = ref(-1)
// 角色详情
const roleDetail = ref<RoleDetailI>({
  perms: [],
  remark: '',
  roleId: -1,
  roleName: '',
  userTotal: 0,
})
// 树形结构实例对象数组
const treeRef = ref()
// 标签页名字
const tabName = ref<'tree' | 'member'>('tree')
// 获取角色列表
const getRoleList = async () => {
  roleList.value = await roleGetRoleListApi()

  if (currentRoleId.value === -1) {
    // 初始化 roleId & roleDetail & roleUserList & roleUserTotal
    currentRoleId.value = roleList.value[0].roleId
    getRoleDetail(currentRoleId.value)
    getRoleUserData(currentRoleId.value)
  }
}
getRoleList()
// 下拉菜单操作
const handleCommand = async (command: string) => {
  if (command === 'edit') {
    router.push({
      path: '/sys/role/add',
      query: { roleId: currentRoleId.value },
    })
  } else if (command === 'del') {
    let content =
      roleDetail.value.userTotal > 0
        ? '删除角色前，请先移除角色内的所有成员。'
        : '删除后该角色下的用户权限失效，是否删除？'
    await ElMessageBox.confirm(content, '', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    if (roleDetail.value.userTotal === 0) {
      // 该角色下没有用户成员了
      await roleDelRoleApi(currentRoleId.value)
      currentRoleId.value = -1
      ElMessage.success('删除成功')
      getRoleList()
    }
  }
}
// 获取权限树
const getPermissionTree = async () => {
  permissionTree.value = await roleGetPermissionTreeApi()
  // 给权限树添加 disabled 属性
  addKey(permissionTree.value, 'disabled')
}
getPermissionTree()
// 获取角色详情
const getRoleDetail = async (roleId: number) => {
  const res = await roleGetRoleDetailApi(roleId)
  roleDetail.value = res
  // 设置权限树选中状态
  treeRef.value.forEach((tree: any, index: number) => {
    tree.setCheckedKeys(res.perms[index])
  })
}
// 切换角色后获取 => 角色详情 & 角色关联的用户列表
const changeRole = async (roleId: number) => {
  currentRoleId.value = roleId
  getRoleDetail(roleId)
  getRoleUserData(roleId)
}
/**
 * 成员区域
 */
// 获取角色关联用户列表的参数
const userListParams = ref<RoleUserListParamsI>({
  page: 1,
  pageSize: 5,
})
// 角色关联的用户列表
const roleUserList = ref<RoleUserListItemI[]>([])
// 角色关联的用户个数
const roleUserTotal = ref(0)
// 获取角色关联的用户数据
const getRoleUserData = async (roleId: number) => {
  const res = await roleGetRoleUserDataApi(roleId, userListParams.value)
  roleUserList.value = res.rows
  roleUserTotal.value = res.total
}
// 页码切换
const changePage = (page: number) => {
  userListParams.value.page = page
  getRoleUserData(currentRoleId.value)
}
// 页码条数切换
const changePageSize = (pageSize: number) => {
  userListParams.value.pageSize = pageSize
  getRoleUserData(currentRoleId.value)
}
</script>

<template>
  <div class="system-role-page">
    <!-- 角色列表 -->
    <div class="left-wrapper">
      <div
        class="role-item"
        :class="{ active: item.roleId === currentRoleId }"
        v-for="item in roleList"
        :key="item.roleId"
        @click="changeRole(item.roleId)"
      >
        <div class="role-info">
          <img
            :src="item.roleId === currentRoleId ? activeUser : user"
            class="icon"
          />
          {{ item.roleName }}
        </div>
        <div class="more">
          <!-- <img src="@/assets/more.svg" class="icon" /> -->
          <el-dropdown
            trigger="click"
            :hide-on-click="true"
            @command="handleCommand"
          >
            <span class="el-dropdown-link">
              <img src="@/assets/more.svg" class="icon" />
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="edit">编辑角色</el-dropdown-item>
                <el-dropdown-item command="del" style="color: red">
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      <el-button
        class="add-btn"
        size="small"
        @click="$router.push('/sys/role/add')"
        >添加角色</el-button
      >
    </div>
    <!-- 权限列表 -->
    <div class="right-wrapper">
      <el-tabs v-model="tabName">
        <el-tab-pane label="功能权限" name="tree">
          <div class="tree-wrapper">
            <div
              class="tree-item"
              v-for="item in permissionTree"
              :key="item.id"
            >
              <div class="tree-title">{{ item.title }}</div>
              <el-tree
                :data="item.children"
                node-key="id"
                ref="treeRef"
                :props="{ label: 'title' }"
                show-checkbox
                default-expand-all
                :expand-on-click-node="false"
              />
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="`成员(${roleUserTotal})`" name="member">
          <div class="user-wrapper">
            <!-- 表格 -->
            <el-table :data="roleUserList" style="width: 100%; height: 400px">
              <el-table-column type="index" width="250" label="序号" />
              <el-table-column prop="name" label="员工姓名" />
              <el-table-column prop="userName" label="登录账号" />
            </el-table>
            <!-- 分页 -->
            <el-pagination
              v-model:current-page="userListParams.page"
              v-model:page-size="userListParams.pageSize"
              :total="roleUserTotal"
              @current-change="changePage"
              @size-change="changePageSize"
              layout="total, prev, pager, next, slot"
            >
              <el-select v-model="userListParams.pageSize" style="width: 95px">
                <el-option label="3条/页" :value="3" />
                <el-option label="5条/页" :value="5" />
                <el-option label="10条/页" :value="10" />
              </el-select>
            </el-pagination>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.system-role-page {
  display: flex;
  font-size: 14px;
  background-color: #fff;

  .left-wrapper {
    width: 200px;
    border-right: 1px solid #e4e7ec;
    padding: 4px;
    text-align: center;

    .role-item {
      position: relative;
      height: 56px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 20px;
      cursor: pointer;

      &.active {
        background: #edf5ff;
        color: #4770ff;
      }
    }

    .role-info {
      display: flex;
      align-items: center;

      .icon {
        margin-right: 10px;
        width: 20px;
      }
    }

    .more {
      display: flex;
      align-items: center;

      .icon {
        width: 15px;
      }
    }

    .add-btn {
      width: 100%;
      margin-top: 20px;
    }
  }

  .right-wrapper {
    flex: 1;

    .tree-wrapper {
      display: flex;
      justify-content: space-between;

      .tree-item {
        flex: 1;
        border-right: 1px solid #e4e7ec;
        padding: 0px 4px;
        text-align: center;

        .tree-title {
          background: #f5f7fa;
          text-align: center;
          padding: 10px 0;
          margin-bottom: 12px;
        }
      }
    }

    :deep(.el-tabs__nav-wrap) {
      padding-left: 20px;
    }

    .user-wrapper {
      padding: 20px;

      // 修改 el-table 表头背景色
      ::v-deep(.el-table__header th) {
        background-color: rgb(244, 246, 248); // 设置你想要的背景色
        color: rgb(43, 37, 37);
        padding: 10px 0;
      }

      .el-pagination {
        display: flex;
        justify-content: flex-end;
        margin: 10px 0px;
      }
    }
  }
}
</style>
